package com.wuliupai.delivery.wuliupaidelivery.activity;

import android.app.Dialog;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.wuliupai.delivery.wuliupaidelivery.App;
import com.wuliupai.delivery.wuliupaidelivery.R;
import com.wuliupai.delivery.wuliupaidelivery.bean.CalculateFreightBean;
import com.wuliupai.delivery.wuliupaidelivery.constants.Flag;
import com.wuliupai.delivery.wuliupaidelivery.constants.InterfaceNet;
import com.wuliupai.delivery.wuliupaidelivery.constants.RequestResultCode;
import com.wuliupai.delivery.wuliupaidelivery.net.NetResultOperate;
import com.wuliupai.delivery.wuliupaidelivery.utils.JsonUtils;
import com.wuliupai.delivery.wuliupaidelivery.utils.NumberUtils;
import com.wuliupai.delivery.wuliupaidelivery.utils.PlaceUtil;
import com.wuliupai.delivery.wuliupaidelivery.utils.StringUtils;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.OnActivityResult;
import org.androidannotations.annotations.ViewById;

/**
 * Descriptions：计算运费
 * <p>
 * Author：ChenME
 * Date：4/15/2017
 * Email：ibelieve1210@163.com
 */
@EActivity(R.layout.activity_calculate_freight)
public class CalculateFreightActivity extends AppBaseActivity {


    @ViewById(R.id.rl_calculateFreightSendAddress)
    RelativeLayout rl_calculateFreightSendAddress;//发货地的布局
    @ViewById(R.id.tv_calculateFreightSelectSendAddress)
    TextView tv_calculateFreightSelectSendAddress;//发货地

    @ViewById(R.id.rl_calculateFreightReceiveAddress)
    RelativeLayout rl_calculateFreightReceiveAddress;//收货地的布局
    @ViewById(R.id.tv_calculateFreightReceiveAddress)
    TextView tv_calculateFreightReceiveAddress;//收货地

    @ViewById(R.id.et_calculateFreightWeight)
    EditText et_calculateFreightWeight;//重量
    @ViewById(R.id.et_calculateFreightVolume)
    EditText et_calculateFreightVolume;//体积

    @ViewById(R.id.ll_calculateResult)
    LinearLayout ll_calculateResult;//计算结果的布局
    @ViewById(R.id.tv_calculateResult)
    TextView tv_calculateResult;//计算结果

    @ViewById(R.id.btn_calculateFreightNext)
    Button btn_calculateFreightNext;//计算运费的按钮

//    @ViewById(R.id.rg_calculateFreight)
//    RadioGroup rg_calculateFreight;//用户类型RadioGroup
//    @ViewById(R.id.rb_calculateFreightZero)
//    RadioButton rb_calculateFreightZero;//普通用户
//    @ViewById(R.id.rb_calculateFreightOne)
//    RadioButton rb_calculateFreightOne;//A类用户
//    @ViewById(R.id.rb_calculateFreightTwo)
//    RadioButton rb_calculateFreightTwo;//B类用户

    @Extra("calculateAct")
    String calculateAct;

    private String startProvince;//出发地省
    private String startCity;//出发地市
    private String startArea;//出发地县

    private String endProvince;//目的地省
    private String endCity;//目的地市
    private String endArea;//目的地县

    private String calculateType = "0";

    @AfterViews
    void startCalculateFreight() {
        setTitle(this, R.string.string_calculate_freight_title, R.drawable.comm_press_return_selector,
                true, new OnNavigationBtnClickListener() {
                    @Override
                    public void navigationClick() {
                        onBackPressed();
                    }

                    @Override
                    public void menuItemClick(MenuItem item) {
                        switch (item.getItemId()) {
                            case R.id.menuItem1:
                                CommonWebViewActivity_.intent(CalculateFreightActivity.this)
                                        .whichPage(CommonWebViewActivity.Page_PriceExplain).start();
                                animUtils.leftInAnimation(CalculateFreightActivity.this);
                                break;
                        }
                    }
                });
        if (calculateAct.equals(Flag.CALCULATE_NO_BACK)) {
            ll_calculateResult.setVisibility(View.VISIBLE);
        } else {
            ll_calculateResult.setVisibility(View.GONE);
        }
//        chargeUserType();
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        menu.findItem(R.id.menuItem1).setVisible(true).setTitle("价格说明");
        menu.findItem(R.id.menuItem2).setVisible(false);
        return false;
    }


    /**
     * 选择寄件地省市县
     */
    @Click(R.id.rl_calculateFreightSendAddress)
    void selectSendAddress() {
        PlaceSelectActivityStep2_.intent(CalculateFreightActivity.this)
                .pageTitle(getString(R.string.string_send_address))
                .startForResult(RequestResultCode.RRC_GetAddressFrom);
        animUtils.popInAnimation(CalculateFreightActivity.this);
    }

    /**
     * 选择收件地省市县
     */
    @Click(R.id.rl_calculateFreightReceiveAddress)
    void selectReceiveAddress() {
        PlaceSelectActivityStep2_.intent(CalculateFreightActivity.this)
                .pageTitle(getString(R.string.string_take_address))
                .startForResult(RequestResultCode.RRC_GetAddressTo);
        animUtils.popInAnimation(CalculateFreightActivity.this);
    }

    @Click(R.id.btn_calculateFreightNext)
    void calculateFreight() {
        calculateResult();
    }

    /**
     * 上传计算费用所需的数据
     */
    private void calculateResult() {
        String weight = String.valueOf(Math.ceil(Double.parseDouble(et_calculateFreightWeight.getText().toString())));
        String volume = String.valueOf(Double.parseDouble(et_calculateFreightVolume.getText().toString()));
        CalculateFreightBean calculate = new CalculateFreightBean(weight, volume, calculateType,
                startProvince, startCity, startArea, "",
                endProvince, endCity, endArea, "", "1", "1");
        String jsonCalculate = JsonUtils.createJsonString(calculate);
        try {
            String aesCalculate = JsonUtils.aes(jsonCalculate);
            callNet(CalculateFreightActivity.this, InterfaceNet.Net_CalculateFreightNew, aesCalculate, new NetResultOperate() {
                @Override
                public void onSuccess(String content) {
                    CalculateFreightBean calculate = (CalculateFreightBean) JsonUtils.parseJsonString(content, CalculateFreightBean.class);
                    if (calculateAct.equals(Flag.CALCULATE_NO_BACK)) {
                        tv_calculateResult.setText((Integer.valueOf(calculate.getFreight()) / 100) + "元");
                    } else {
                        Intent intent = new Intent();
                        intent.putExtra("calculate", calculate.getFreight());
                        setResult(Flag.ACTIVITY_CALCULATE_BACK, intent);
                        finish();
                        animUtils.leftInAnimation(CalculateFreightActivity.this);
                    }
                }

                @Override
                public void onDataEmpty(String content) {

                }

                @Override
                public void onDataEnd(String content) {

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 计算体积
     */
    @Click(R.id.tv_calculateVolumeBtn)
    void calculateVolumeClick() {

        Dialog view = new Dialog(this, R.style.DialogFullWindowStyle);// 创建自定义样式dialog

        view.setCancelable(false);// 不可以用“返回键”取消
        view.setContentView(R.layout.dialog_calculate_volume);// 设置布局

        EditText et_length = (EditText) view.findViewById(R.id.et_length);
        EditText et_width = (EditText) view.findViewById(R.id.et_width);
        EditText et_height = (EditText) view.findViewById(R.id.et_height);


        view.findViewById(R.id.btn_confirm).setOnClickListener(v -> {
            String lengthTemp = et_length.getText().toString().trim();
            String widthTemp = et_width.getText().toString().trim();
            String heightTemp = et_height.getText().toString().trim();
            if (StringUtils.isEmpty(lengthTemp) ||
                    StringUtils.isEmpty(widthTemp) ||
                    StringUtils.isEmpty(heightTemp)) {
                App.toast("请填入完整的货物体积信息！");
                return;
            }
            double result = Double.valueOf(lengthTemp) *
                    Double.valueOf(widthTemp) *
                    Double.valueOf(heightTemp) / 1000000;
            et_calculateFreightVolume.setText(NumberUtils.formatDouble(result, "0.00") + "");
            view.dismiss();
        });

        view.findViewById(R.id.iBtn_close).setOnClickListener(v -> view.dismiss());
        view.show();
    }

    /**
     * 寄件地回调
     *
     * @param resultCode
     * @param data
     */
    @OnActivityResult(RequestResultCode.RRC_GetAddressFrom)
    void onResultSend(int resultCode, Intent data) {
        if (PlaceSelectActivityStep2.Result_SelectPlace == resultCode) {
            String sProvinceName = PlaceUtil.resultDispose(data).get(PlaceUtil.Index_ProvinceName);
            String sCityName = PlaceUtil.resultDispose(data).get(PlaceUtil.Index_CityName);
            String sAreaName = PlaceUtil.resultDispose(data).get(PlaceUtil.Index_AreaName);
            tv_calculateFreightSelectSendAddress.setText(sProvinceName + "-" + sCityName + "-" + sAreaName);
            startProvince = data.getStringArrayExtra("province")[0];
            startCity = data.getStringArrayExtra("city")[0];
            startArea = data.getStringArrayExtra("area")[0];
        }
    }

    /**
     * 选择用户类型
     */
//    private void chargeUserType() {
//        rg_calculateFreight.setOnCheckedChangeListener((radioGroup, checkedId) -> {
//            if (checkedId == rb_calculateFreightZero.getId()) {
//                calculateType = "0";
//            } else if (checkedId == rb_calculateFreightOne.getId()) {
//                calculateType = "1";
//            } else {
//                calculateType = "2";
//            }
//        });
//    }

    /**
     * 收件地回调
     *
     * @param resultCode
     * @param data
     */
    @OnActivityResult(RequestResultCode.RRC_GetAddressTo)
    void onResultReceive(int resultCode, Intent data) {
        if (PlaceSelectActivityStep2.Result_SelectPlace == resultCode) {
            String eProvinceName = PlaceUtil.resultDispose(data).get(PlaceUtil.Index_ProvinceName);
            String eCityName = PlaceUtil.resultDispose(data).get(PlaceUtil.Index_CityName);
            String eAreaName = PlaceUtil.resultDispose(data).get(PlaceUtil.Index_AreaName);
            tv_calculateFreightReceiveAddress.setText(eProvinceName + "-" + eCityName + "-" + eAreaName);

            endProvince = data.getStringArrayExtra("province")[0];
            endCity = data.getStringArrayExtra("city")[0];
            endArea = data.getStringArrayExtra("area")[0];
        }
    }
}